import { Book, Theme, ThemeBook } from '../models';
import book from './book';

export default function (router) {
  /**
   * 后台获取主题书籍
   */
  router.get('/api/admin/theme-books', async ctx => {
    const { theme, search } = ctx.request.query;
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    if (!theme) await ctx.json(false, '参数错误');
    const queryParam = {};
    if (search) {
      const reg = new RegExp(search.toString('utf8').trim(), 'i');
      queryParam.name = reg;
    }
    const total = await ThemeBook.countDocuments({ theme });
    const thisTheme = await ThemeBook.find({ theme })
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, create_time: 1 })
      .populate({
        path: 'book',
        options: {
          match: queryParam,
          select: 'name author img_url des classify create_time'
        }
      });

    await ctx.json(true, '获取主题中书籍成功', { list: thisTheme, total });
  });

  /**
   * 后台给主题新增书籍
   */
  router.post('/api/admin/theme-books', async ctx => {
    const { theme, books } = ctx.request.body;
    if (!theme || !books || book.length <= 0) await ctx.json(false, '参数错误');
    const thisTheme = await ThemeBook.find({ theme });
    if (!thisTheme) await ctx.json(false, '主题不存在');
    const curThemeBooks = await ThemeBook.countDocuments({ theme });
    const addBooks = [];
    for (let i = 0; i < books.length; i++) {
      const thisBook = await Book.findById(books[i], '_id name');
      const thisThemeBooks = await ThemeBook.findOne({ theme, book: books[i] });
      if (thisBook && !thisThemeBooks) {
        await ThemeBook.create({
          theme: ctx.transId(theme),
          book: ctx.transId(books[i]),
          priority: curThemeBooks + 1 + i,
          create_time: new Date()
        });
        await Theme.updateOne({ _id: theme }, { $set: { book_num: curThemeBooks + 1 + i } });
        addBooks.push(thisBook.name);
      }
    }
    if (addBooks.length > 0) {
      await ctx.json(true, '新增主题书籍成功', addBooks);
    } else {
      await ctx.json(false, '书籍已存在与主题中，请勿重复添加');
    }
  });

  /**
   * 后台给主题排序书籍
   */
  router.post('/api/admin/theme-books/exchange', async ctx => {
    const { from: fromIndex, to: toIndex, theme, book } = ctx.request.body;
    if (!fromIndex || !toIndex || !theme || !book) await ctx.json(false, '参数错误');
    if (fromIndex === toIndex) await ctx.json(false, '交换顺序不能相同');

    let updateCur, updateOther;
    if (fromIndex > toIndex) {
      updateOther = await ThemeBook.updateMany({ theme, priority: { $lt: fromIndex, $gte: toIndex } }, { $inc: { priority: 1 } });
      updateCur = await ThemeBook.updateOne({ theme, book }, { $set: { priority: toIndex } });
    } else {
      updateOther = await ThemeBook.updateMany({ theme, priority: { $gt: fromIndex, $lte: toIndex } }, { $inc: { priority: -1 } });
      updateCur = await ThemeBook.updateOne({ theme, book }, { $set: { priority: toIndex } });
    }

    if (updateCur.ok && updateOther.ok) {
      await ctx.json(true, '交换成功');
    } else {
      await ctx.json(false, '交换失败');
    }
  });

  /**
   * 后台给主题删除书籍
   */
  router.delete('/api/admin/theme-books', async ctx => {
    const { theme, book } = ctx.request.body;
    console.log(theme, book);
    if (!theme || !book) await ctx.json(false, '参数错误');
    const thisData = await ThemeBook.findOne({ theme, book }, 'priority');
    const operation = await ThemeBook.deleteMany({ theme, book });
    // 更新顺序
    const update = await ThemeBook.updateMany({ theme, priority: { $gt: thisData.priority } }, { $inc: { priority: -1 } });
    if (operation.ok && update.ok) {
      await ctx.json(true, '删除主题书籍成功');
    } else {
      await ctx.json(false, '删除主题书籍失败');
    }
  });
}
